package com.lzm.toolfx.controller;

import animatefx.animation.*;
import com.lzm.toolfx.common.SVGFiles;
import com.lzm.toolfx.utils.DialogUtils;
import com.bltec.toolfx.view.*;
import com.lzm.toolfx.view.*;
import de.felixroske.jfxsupport.AbstractFxmlView;
import de.felixroske.jfxsupport.FXMLController;
import de.felixroske.jfxsupport.GUIState;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.effect.Glow;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.shape.SVGPath;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javax.annotation.Resource;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static de.felixroske.jfxsupport.GUIState.getStage;

@FXMLController
public class ConsoleController implements Initializable {
    @FXML
    AnchorPane ap_console;
    @FXML
    AnchorPane ap_content;
    @FXML
    AnchorPane ap_bottom;
    @FXML
    Button btn_fullScreen;
    @FXML
    SVGPath sp_fullScreen;
    @FXML
    HBox hb_user;
    @FXML
    Label lb_userName;
    @FXML
    Button btn_userHead;
    @FXML
    ColorPicker picker;
    @FXML
    HBox hb_function;

    @FXML
    Button btn_builder;
    @FXML
    Button btn_location;
    @FXML
    Button btn_person;
    @FXML
    Button btn_track;
    @FXML
    Button btn_alert;
    @FXML
    Button btn_attendance;
    @FXML
    Button brn_assert;
    @FXML
    Button btn_camera;
    @FXML
    Button btn_gate;
    @FXML
    Button btn_visual;
    @FXML
    Label lb_test;

    @Resource
    SysTray sysTray;
    @Resource
    BuilderView builder;
    @Resource
    LocationView location;
    @Resource
    PerformanceView performance;
    @Resource
    CameraView camera;
    @Resource
    PersonView person;
    @Resource
    AlertView alert;
    @Resource
    AssertView assertView;
    @Resource
    AttendanceView attendance;
    @Resource
    GateView gate;
    @Resource
    TrackView track;
    @Resource
    VisualView visual;
    @Resource
    UserPane userPane;

    private Stage stage =  getStage();
    private Stage user;

    @Override
    public void initialize(URL location, ResourceBundle resources){
        stage.setResizable(true);
        try {
            GUIState.getSystemTray().add(sysTray.getTrayIcon());
        }catch (Exception e){
            sysTray.getTrayIcon().displayMessage("错误",e.getLocalizedMessage(), TrayIcon.MessageType.ERROR);
        }
        //HBoxNodeDragUtil.addAllDragListener(lb_test,hb_function,hb_function.getChildren());
        user = new Stage();
        user.setTitle("Bl Cloud");
        user.initModality(Modality.APPLICATION_MODAL);
        user.initStyle(StageStyle.UTILITY);
        user.setResizable(false);
        Parent root = userPane.getView();
        Scene scene = new Scene(root);
        user.setScene(scene);
        /*窗体最大/最小事件*/
        stage.maximizedProperty().addListener((observable, oldValue, newValue) -> {
            //svg_max_icon.setContent(newValue ? SVGFiles.DE_MAX : SVGFiles.MAX);
        });
        stage.setOnCloseRequest(event -> {
            CheckBox rem = new CheckBox("记住我的选择");
            DialogUtils dialog = new DialogUtils(new DialogUtils.Builder()
                    .setAlertType(Alert.AlertType.NONE)
                    .setTitle("确认?")
                    .setHeadText("确认关闭吗?")
                    .setButtonTypes(
                            new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE),
                            new ButtonType("退出", ButtonBar.ButtonData.NO),
                            new ButtonType("最小化", ButtonBar.ButtonData.YES))
                    .setContentElements(rem)
            );
            dialog.getNode(rem).setOnMouseClicked(event1 -> {
                //System.out.println(rem.isSelected());
            });
            Optional<ButtonType> btn = dialog.showAndWait();
            switch (btn.get().getButtonData()){
                case NO:
                    GUIState.getSystemTray().remove(sysTray.getTrayIcon());//Remove SystemTray icon
                    Platform.exit();
                    break;
                case YES:
                    Platform.setImplicitExit(false);
                    Platform.runLater(stage::hide);
                    break;
                case CANCEL_CLOSE:
                    event.consume();//阻止窗口关闭
                    break;
            }
        });
        /*系统托盘事件*/
        sysTray.getTrayIcon().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                //双击左键
                if (e.getButton() == java.awt.event.MouseEvent.BUTTON1) {
                    Platform.setImplicitExit(false);
                    if (SystemTray.isSupported()) {
                        Platform.runLater(() -> {
                            if (GUIState.getStage().isShowing()){
                                GUIState.getStage().toFront();
                            }
                            else
                                GUIState.getStage().show();
                        });
                    } else {
                        sysTray.getTrayIcon().displayMessage("错误", "当前系统不支持最小化到系统托盘", TrayIcon.MessageType.ERROR);
                    }
                } else if (e.getButton() == java.awt.event.MouseEvent.BUTTON3) {
                }
            }
        });
        setNotify();
    }

    private void setNotify(){
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        service.scheduleAtFixedRate(()->{
            //sysTray.getTrayIcon().displayMessage("错误", "当前系统不支持最小化到系统托盘", TrayIcon.MessageType.ERROR);
        },0,1000, TimeUnit.MILLISECONDS);
    }

    @FXML
    private void  pickColor(ActionEvent event){
        // linear-gradient(to top,#c08eaf60,#ffffff00)
        String color = "-fx-background-color: linear-gradient(to top,#" + picker.getValue().toString().substring(2,8)+"60,#ffffff00)";
        ap_console.setStyle(color);
    }

    @FXML
    private void toLogin(){
        user.show();
    }
    @FXML
    private void setFullScreen(){
        sp_fullScreen.setContent(stage.isFullScreen()? SVGFiles.MAX : SVGFiles.DE_MAX );
        stage.setFullScreen(!stage.isFullScreen());
    }
    @FXML
    private void location(ActionEvent event){
        setContent(event,ap_content,location);
    }
    @FXML
    private void performance(ActionEvent event){
        setContent(event,ap_bottom,performance);
    }
    @FXML
    private void camera(ActionEvent event){
        setContent(event,ap_content,camera);
    }
    @FXML
    private void builder(ActionEvent event){
        setContent(event,ap_content,builder);
    }
    @FXML
    private void assertView(ActionEvent event){
        setContent(event,ap_content,assertView);
    }
    @FXML
    private void attendance(ActionEvent event){
        setContent(event,ap_content,attendance);
    }
    @FXML
    private void alert(ActionEvent event){
        setContent(event,ap_content,alert);
    }
    @FXML
    private void track(ActionEvent event){
        setContent(event,ap_content,track);
    }
    @FXML
    private void gate(ActionEvent event){
        setContent(event,ap_content,gate);
    }
    @FXML
    private void visual(ActionEvent event){
        setContent(event,ap_content,visual);
    }
    @FXML
    private void person(ActionEvent event){
        setContent(event,ap_content,person);
    }

    /**Set content AnchorPane's Children Node
     * @param  view AbstractFxmlView
     */
    Object current_eventSrc = null;
    int last_index = 0;
    private void setContent(ActionEvent eventSrc,AnchorPane pane, AbstractFxmlView view){
        int clickIndex = 0;
        if(!eventSrc.getSource().equals(current_eventSrc)){
            current_eventSrc = eventSrc.getSource();
            for(Node node : hb_function.getChildren()){
                if(!node.equals(eventSrc.getSource())){
                    node.setScaleX(1.0);
                    node.setScaleY(1.0);
                    node.setEffect(null);
                    node.setStyle("-fx-background-color: #00000000;-fx-border-color: #00000000");
                }
                else{
                    clickIndex = hb_function.getChildren().indexOf(node);
                    node.setScaleX(1.1);
                    node.setScaleY(1.1);
                    node.setEffect(new Glow(0.5));
                    node.setStyle("-fx-background-color: #00000005;-fx-background-radius: 10;-fx-border-color: #ccc;-fx-border-radius: 10;-fx-border-width: 0.5");
                }
            }

            pane.getChildren().clear();
            AnchorPane.setTopAnchor(view.getView(),0.0);
            AnchorPane.setBottomAnchor(view.getView(),0.0);
            AnchorPane.setLeftAnchor(view.getView(),0.0);
            AnchorPane.setRightAnchor(view.getView(),0.0);
            pane.getChildren().addAll(view.getView());
            if(clickIndex>last_index){
                new SlideInRight(pane).setSpeed(4.0).play();
            }else {
                new SlideInLeft(pane).setSpeed(4.0).play();
            }
            last_index = clickIndex;
        }else {
            new Tada((Node) eventSrc.getSource()).setSpeed(1.5).play();
        }
        //pane.getChildren().clear();//First. clear all child node

    }
}
